const MongoClient = require("mongodb").MongoClient;
const config = require("./config.json").mongodb;

module.exports = {
    /**
     * 
     * @param {number} chatId Telegram chat id.
     * @param {string} url Git repository's url.
     * @returns {Promise<object>} Chat object if one is found, otherwise null.
     */
    async getPassword(chatId, url) {
        const client = await MongoClient.connect(config.url);
        try {
            const collection = client.db(config.dbName).collection("chats");
            const chat = await collection.findOne({
                chatId,
                url
            });
            return chat;
        } finally {
            client.close();
        }
    },

    /**
     * 
     * @param {number} chatId Telegram chat id.
     * @param {string} url Git repository's url.
     * @param {string} password Password for gitee webhooks.
     */
    async saveChat(chatId, url, password) {
        const client = await MongoClient.connect(config.url);
        try {
            const collection = client.db(config.dbName).collection("chats");
            await collection.insertOne({
                chatId,
                url,
                password
            });
        } finally {
            client.close();
        }
    },

    /**
     * 
     * @param {string} url Git repository's url.
     * @param {string} password Password for gitee webhooks.
     * @returns {Promise<object>} Chat object if one is found, otherwise null.
     */
    async getChatId(url, password) {
        const client = await MongoClient.connect(config.url);
        try {
            const collection = client.db(config.dbName).collection("chats");
            const chat = await collection.findOne({
                url,
                password
            });
            return chat;
        } finally {
            client.close();
        }
    }
};